import { Component, OnInit, ViewChild } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';

import { of } from 'rxjs/observable/of';
import { catchError, map, tap } from 'rxjs/operators';

import { Task } from './task.model';

import { ModalDirective } from 'ngx-bootstrap/modal';

import { FormControl, FormGroup } from '@angular/forms';

@Component({
  selector: 'app-task',
  templateUrl: './task.component.html',
  styleUrls: ['./task.component.css',
      '../app.component.css']
})
export class TaskComponent implements OnInit {
    private headers = new HttpHeaders({'Content-Type': 'application/x-www-form-urlencoded'});
    url = 'http://edu.xk.com/xkapi'; 
    addOrEdit:string = 'add';
    dayMs = 24*60*60*1000;
    exportDay = 7; //导出设置7day
    data = [];
    array = [];

    activeMenu = 'task';

    size: number = 10;    
    index: number;     //要先声明 

    searchLesson:string = '';
    searchTeacher:string = '';
    searchCommunity:string = '';

    course = [];
    communities = [];
    id: number = 0;
    communityId:string = '';
    lessionId:string = '';
    content:string = '';
    deleteId : number = 0;

    bsValue: Date = new Date();
    bsValueEnd: Date = new Date();
    mytime: any = '00';
    mytimeEnd: any = '00';
    /* 分页，start*/
    maxSize: number = 5;
    bigTotalItems: number = 50000; //总数
    bigCurrentPage: number = 1; //当前页
    numPages: number = 0;   //总页数
    pageChanged(event: any): void {
      this.bigCurrentPage = event.page;
      this.getTasks(event.page, 10);
      console.log('Page changed to: ' + event.page);
      console.log('Number items per page: ' + event.itemsPerPage);
    }
    /* 分页，end*/
    getTasks(pagenumber, pagesize){
        let taskReqParams = {
            page: pagenumber,
            size: pagesize,
            lessonName: this.searchLesson.trim(),
            teacherName: this.searchTeacher.trim(),
            communityName: this.searchCommunity.trim(),
        };
        let taskReqParam = `page=${pagenumber}&size=10&lessonName=${this.searchLesson.trim()}&teacherName=${this.searchTeacher.trim()}&communityName=${this.searchCommunity.trim()}`;
        return this.http.post(`${this.url}/task/findAllByQueryAndPage`, taskReqParam, { 'headers': this.headers} ).subscribe(
          result => {
              if(result) {
                  if (result['status'] == 200) {
                      this.data = result['data'];
                      this.array = this.data['content'];
                      this.bigTotalItems = this.data['totalElements']; //总数
                      this.numPages = this.data['totalPages'];   //总页数
                  } else {
                      console.log(result['desc']);
                  }
              }
          }
      );
    }
    getLessions(){
      return this.http.get(`${this.url}/lesson/findAll`).subscribe(
          result => {
              if(result) {
                  if (result['status'] == 200) {
                      this.course = result['data'];
                  } else {
                      console.log(result['desc']);
                  }
              }
          }
      );
    }
    getCommunities(){
      return this.http.get(`${this.url}/community/findAll`).subscribe(
          result => {
              if(result) {
                  if (result['status'] == 200) {
                      this.communities = result['data'];
                  } else {
                      console.log(result['desc']);
                  }
              }
          }
      );
    }
    // search
    search() {
        this.bigCurrentPage = 1;
        this.getTasks(1, 10);
    }
    clear() {
        this.searchLesson = '';
        this.searchTeacher = '';
        this.searchCommunity = '';

        this.search();
    }
    change2search () {
        setTimeout(function() {
          this.search();
        }, 1000);
    }
    //添加和编辑 提交按钮
    onSubmit(id, lessionId, communityId, bsValue, mytime, bsValueEnd, mytimeEnd, content, addModal):void {
        let that = this;
        let reqUrl = this.addOrEdit === 'add' ? `${this.url}/task/add` : `${this.url}/task/update`;
        let startTime: number = Math.floor(parseInt(bsValue.getTime())/this.dayMs)*this.dayMs + Math.floor(mytime.getTime() % this.dayMs);
        let endTime: number = Math.floor(parseInt(bsValueEnd.getTime())/this.dayMs)*this.dayMs + Math.floor(mytimeEnd.getTime() % this.dayMs);
        console.log('form startTime:'+  startTime);
        this.http.get(`${reqUrl}?id=${id}&lessonId=${lessionId}&communityId=${communityId}&startTime=${startTime}&endTime=${endTime}&content=${content}`).subscribe(
          result => {
            if(result) {
              if (result['status'] == 200) {
                  that.getTasks(1, 10); //要this
                  that.bigCurrentPage = 1;

                  that.bsValue = new Date();
                  that.bsValueEnd = new Date();
                  that.mytime = '00';
                  that.mytimeEnd = '00'
                  addModal.hide();
              } else {
                  console.log(result['desc']);
              }
            }
          }
        );
    }
    //添加
    addNew(addModal) {
        addModal.show();

        this.addOrEdit = 'add';
        this.id = 0;
        this.lessionId = '';
        this.communityId = '';
        this.content = '';
    }
    // 编辑 按钮
    edit(item, addModal) {  
        console.log('item:');
        console.log(item);

        addModal.show();

        this.addOrEdit = 'edit';
        this.id = item.id;
        this.lessionId = item.lessonId;
        this.communityId = item.communityId;
        this.content = item.content;
        this.bsValue = new Date(item.startTime);
        this.bsValueEnd = new Date(item.endTime);
        this.mytime = new Date(item.startTime);
        this.mytimeEnd = new Date(item.endTime);
    }
    //删除按钮
    delete(item, deleteModal){  
        deleteModal.show();
        console.log('delete');
        this.deleteId= item.id;
    }
    //删除 确认
    deleteConfirm(item,deleteModal) {  
        console.log('item:');
        console.log(item);
        return this.http.get(`${this.url}/task/delete?id=${this.deleteId}`).subscribe(
          result => {
              if(result) {
                  this.getTasks(1, 10)  //要this
                  this.bigCurrentPage = 1;
                  deleteModal.hide();
              } else {
                  console.log(result['desc']);
              }
          }
      );
    }
    // 导出
    export() {
        window.open(`${this.url}/task/download?day=${this.exportDay}&status=1`);
    }
    //导入
    upload(uploadModal) {
        uploadModal.show();
    }
    uploadConfirm(uploadModal) {
       // document.getElementById("zz").submit();
        uploadModal.hide();
    }

    constructor(private http: HttpClient){ }

    ngOnInit() {
      this.getTasks(1,10)  //要this
      this.getLessions();
      this.getCommunities();
    }
}
